package com.example.socket;

import java.net.InetSocketAddress;

import javax.annotation.PostConstruct;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SocketServer {
   private static Logger logger=LoggerFactory.getLogger(SocketServer.class);
   @Value("${socket.port}")
	private int port;
   @Value("${socket.boolean}")
    private boolean isSocket;
   @Autowired
   IoAcceptor ioAcceptor;
   @Autowired
   LoggingFilter loggingFilter; 
   @Autowired
   ProtocolCodecFilter protocolCodecFilter;
   @Autowired
   ServerHandler serverHandler;
   
   @PostConstruct
   public void init(){
	   logger.info("socket 通道是否开启:{}",isSocket);
	   if(isSocket){
		   try{
			   ioAcceptor.getFilterChain().addLast("logger",loggingFilter);
			   ioAcceptor.getFilterChain().addLast("codec",protocolCodecFilter);
			   ioAcceptor.setHandler(serverHandler);
			   ioAcceptor.getSessionConfig().setReadBufferSize(2048);
			   ioAcceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
			   ioAcceptor.bind(new InetSocketAddress(port));
		   }catch(Exception e){
			   e.printStackTrace();
		   }
	   }
	   
   }
}
